package com.wangyi.fightimg.moduls.main;

import android.os.Handler;
import android.os.Looper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.ddrx.refresh.SwipeRefresh;
import com.ddrx.refresh.SwipeRefreshLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.tauth.IUiListener;
import com.wangyi.fightimg.R;
import com.wangyi.fightimg.application.MyApplication;
import com.wangyi.fightimg.base.BaseFragment;
import com.wangyi.fightimg.moduls.MainActivity;
import com.wangyi.fightimg.utils.ConstantUtil;
import com.wangyi.fightimg.utils.http.NetResponse;
import com.wangyi.fightimg.utils.http.OkHttpUtil;
import com.wangyi.fightimg.utils.http.ServiceUrl;
import com.wangyi.fightimg.utils.http.download.DownloadImg;
import com.wangyi.fightimg.utils.http.download.DownloadListener;
import com.wangyi.fightimg.widget.sharepopup.SharePopupWindow;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;

/**
 * @author wangYi
 *         首页
 */

public class MainFragment extends BaseFragment implements MainFragmentAdapter.OnItemClickListener {
    @Bind(R.id.rv_imgs)
    RecyclerView rvImgs;// 图片列表
    @Bind(R.id.srl_refresh)
    SwipeRefreshLayout srlRefresh;// 上拉，下拉
    @Bind(R.id.tv_title)
    TextView tvTitle;// 标题

    private MainFragmentAdapter adapter;// 图片列表适配器
    private List<MainFragmentBean> beanList = new ArrayList<>();
    private int currentPageNum = 1;// 当前获取数据页数
    private boolean hasNextPage = false;// 是否有下一页
    private SharePopupWindow sharePopupWindow;// 分享弹框
    private String imgUri;// 分享图片的本地地址
    private IWXAPI api;// 微信aip
    public IUiListener iUiListener;// QQ分享监听

    @Override
    protected int addLayout() {
        return R.layout.fragment_main;
    }

    @Override
    protected void findView() {
        ButterKnife.bind(this, rootView);
        tvTitle.setText("首页");
    }

    @Override
    protected void addListener() {
        // 上拉加载
        srlRefresh.setOnPullUpRefreshListener(new SwipeRefreshLayout.OnPullUpRefreshListener() {
            @Override
            public void onPullUpRefresh() {
                if (hasNextPage) {
                    currentPageNum++;
                    getDataFromServer(currentPageNum, false, false);
                } else {
                    srlRefresh.setPullUpRefreshing(false);
                }
            }
        });
        // 下拉刷新
        srlRefresh.setOnRefreshListener(new SwipeRefresh.OnRefreshListener() {
            @Override
            public void onRefresh() {
                currentPageNum = 1;
                getDataFromServer(currentPageNum, false, true);
            }
        });
    }

    @Override
    protected void initializedPage() {
        iUiListener = ((MainActivity) getActivity()).iUiListener;
        api = ((MyApplication) context.getApplicationContext()).getApi();
        srlRefresh.setColorSchemeResources(R.color.LIGHT_BLUE, R.color.GREEN, R.color.BLUE, R.color.RED);
        srlRefresh.setMode(SwipeRefresh.Mode.BOTH);

        StaggeredGridLayoutManager gridLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
        rvImgs.setLayoutManager(gridLayoutManager);

        rvImgs.getItemAnimator().setChangeDuration(0);
        rvImgs.getItemAnimator().setAddDuration(0);
        rvImgs.getItemAnimator().setChangeDuration(0);
        rvImgs.getItemAnimator().setMoveDuration(0);
        rvImgs.getItemAnimator().setRemoveDuration(0);
        ((SimpleItemAnimator) rvImgs.getItemAnimator()).setSupportsChangeAnimations(false);

        adapter = new MainFragmentAdapter(context, beanList);
        adapter.setCheckChangeListtener(this);
        rvImgs.setAdapter(adapter);
        currentPageNum = 1;
        getDataFromServer(currentPageNum, false, true);
    }

    /**
     * 从服务器获取数据
     *
     * @param pageNum
     * @param showDialog
     * @param isRefresh
     */
    private void getDataFromServer(int pageNum, boolean showDialog, final boolean isRefresh) {
        Map<String, String> params = new HashMap<>();
        params.put("pageNum", "" + pageNum);
        params.put("pageSize", "" + 20);
        OkHttpUtil.getInstance(context).get(ServiceUrl.LIST_INDEX, params, showDialog, new NetResponse<ResponseBody>() {

            @Override
            public void succeed(JSONObject success) {
                JSONObject jsonObject = success.optJSONObject("result");
                hasNextPage = jsonObject.optBoolean("hasNextPage");
                Gson gson = new Gson();
                List<MainFragmentBean> data = gson.fromJson(jsonObject.optString("list"), new TypeToken<List<MainFragmentBean>>() {
                }.getType());
                if (isRefresh) {
                    beanList.clear();
                    if (data != null) {
                        beanList.addAll(data);
                        adapter.notifyDataSetChanged();
                    }
                } else {
                    if (data != null) {
                        beanList.addAll(data);
                        adapter.notifyItemRangeInserted(beanList.size() - data.size(), data.size());
                    }
                }

                if (null != srlRefresh) {
                    if (srlRefresh.isRefreshing()) {
                        srlRefresh.setRefreshing(false);
                    } else if (srlRefresh.ismRefreshingForBottom()) {
                        srlRefresh.setPullUpRefreshing(false);
                    }
                }
            }

            @Override
            public void fail(String error) {
                if (null != srlRefresh) {
                    if (srlRefresh.isRefreshing()) {
                        srlRefresh.setRefreshing(false);
                    } else if (srlRefresh.ismRefreshingForBottom()) {
                        srlRefresh.setPullUpRefreshing(false);
                    }
                }
            }
        });
    }

    @Override
    public void setOnClickListener(final View view, final int position) {
        if (view.getId() == R.id.tv_category) {
            beanList.get(position).setCheck(true);
            beanList.get(position).setCount(beanList.get(position).getCount() + 1);
            adapter.notifyItemChanged(position, "1");
        } else if (view.getId() == R.id.iv_share) {
            String imgUrl = (String) view.getTag();
            imgUri = ConstantUtil.imgUriBas + "/" + imgUrl.split("/")[imgUrl.split("/").length - 1];
            File file = new File(imgUri);
            if (file.exists()) {
                showPopupWindow();
            } else {
                File fileDir = new File(ConstantUtil.imgUriBas);
                if (!fileDir.exists()) {
                    fileDir.mkdirs();
                }
//                requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, 1, null);

                DownloadImg.getInstance(context).startDownload(imgUrl, new DownloadListener() {
                    @Override
                    public void onSuccess() {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                showPopupWindow();
                            }
                        });
                    }

                    @Override
                    public void onFaile(String error) {

                    }
                });
            }
        }

    }

    /**
     * 展示分享平台弹框
     */
    private void showPopupWindow() {
        final WindowManager.LayoutParams layoutParams = getActivity().getWindow().getAttributes();
        layoutParams.alpha = 0.3f;
        getActivity().getWindow().setAttributes(layoutParams);
        if (sharePopupWindow == null) {
            sharePopupWindow = new SharePopupWindow(getActivity(), api, iUiListener);
            sharePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    layoutParams.alpha = 1f;
                    getActivity().getWindow().setAttributes(layoutParams);
                }
            });
        }
        sharePopupWindow.setImgUri(imgUri);
        sharePopupWindow.showAtLocation(rootView.findViewById(R.id.tv_title), Gravity.BOTTOM | Gravity.CENTER, 0, 0);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
